<?php


namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

/**
 * 数据返回中间件
 * Class Response
 * @package SocialBird\Middleware\Middleware
 */
class Response
{
    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 处理下跨域请求
        $isAjax = $request->ajax();
        if ('options' == strtolower($request->getMethod())) {
            $response = new \Illuminate\Http\Response();
            $response->withHeaders([
                'Content-Type' => $isAjax ? 'application/json;charset:UTF-8' : 'text/html;charset=UTF-8',
                'Access-Control-Allow-Origin' => '*',
                'Access-Control-Allow-Credentials' => 'true',
                'Access-Control-Allow-Methods' => 'PUT,GET,POST,DELETE,OPTIONS',
                'Access-Control-Allow-Headers' => 'Content-Type,token,X-Requested-With,Authorization,Language-Set,client-type',
                'Access-Control-Expose-Headers' => '*'
            ]);

            return $response;
        }

        //去除请求参数左右两边空格
        $params = $request->all();
        foreach ($params as $k => $v) {
            if (!is_array($v)) {
                $params[$k] = trim($v);
            }
        }
        $request->replace($params);
        $response = $next($request);
        if ($response->getStatusCode() / 100 == 2 && empty($response->exception)) {
            // 文件下载或者网页访问请求直接返回
            if ($response->headers->get('content-disposition')
                || $response->headers->get('content-type') == 'text/html;charset=utf-8'
                || $this->isBlade($response)
            ) {
                return $response;
            }
            if ($isAjax) {
                $content = [
                    'code' => 0,
                    'message' => 'ok',
                    'data' => $this->getData($response->getContent()),
                ];
                $response->setContent(json_encode($content, JSON_UNESCAPED_UNICODE));
            }
        } else if (!$isAjax) {
            $content = $this->getData($response->getContent());
            $response->setContent($content['msg'] ?? '');
        }
        if (!($response instanceof StreamedResponse)) {
            $response->withHeaders([
                'Content-Type' => $isAjax ? 'application/json;charset:UTF-8' : 'text/html;charset=UTF-8',
                'Access-Control-Allow-Origin' => '*',
                'Access-Control-Allow-Credentials' => 'true',
                'Access-Control-Allow-Methods' => 'PUT,GET,POST,DELETE,OPTIONS',
                'Access-Control-Allow-Headers' => 'Content-Type,token,X-Requested-With,Authorization,Language-Set,client-type',
                'Access-Control-Expose-Headers' => '*'
            ]);
        }
        return $response;
    }

    /**
     * 是否为json格式的字符串
     * @param $string
     * @return bool
     */
    private function isJson($string)
    {
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }

    /**
     * 是否开启事务
     * @param Request $request
     * @return bool
     */
    private function mTrans($request){
        if(/*strtolower($request->method())!='get' && */config('database.transaction')){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 获取response对象数据
     * @param $content
     * @return mixed
     */
    private function getData($content)
    {
        $data = json_decode($content, true);
        return (json_last_error() == JSON_ERROR_NONE) ? $data : $content;
    }

    /**
     * 判断$response 是否为html View
     * @param  $response Illuminate\Http\Response
     * @return bool
     */
    private function isBlade($response)
    {
        $originalContent = $response->getOriginalContent();
        return gettype($originalContent) === 'object' && get_class($originalContent) === 'Illuminate\View\View';
    }


}
